package com.why.simpleboot.core.server.netty;

import com.why.simpleboot.core.common.HttpRequestConstant;

import com.why.simpleboot.core.server.netty.handler.HttpRequestHandlerChainFactory;
import com.why.simpleboot.core.server.netty.response.SimpleResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: why-simpleboot-framework
 * @description:负责处理http请求
 * @author: @why
 * @create: 2021-05-22 14:19
 **/
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private Logger log = LoggerFactory.getLogger(HttpRequestHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
//        得到请求的uri  该uri包含了url，也包含了get请求中的各种参数。
        String uri = request.uri();
        if (uri.contains(HttpRequestConstant.FAVICON.getContent())) {
            return;
        }
        try {
            //从工厂获取到一个处理器链  处理该请求
            FullHttpResponse response = HttpRequestHandlerChainFactory.handleRequestByChain(request);
            ctx.write(response);
            if (!HttpUtil.isKeepAlive(request)) {
                ctx.close();
            }
        } catch (Exception e) {
            ctx.writeAndFlush(SimpleResponse.createError(request.uri(),"在处理请求的时候发生了些意想不到的错误",
              HttpResponseStatus.INTERNAL_SERVER_ERROR));
            log.error("在处理请求的时候发生了些错误", e);
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("异常：", cause);
        ctx.close();
    }

    /**
     * 处理完成关闭程序
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


}
